package com.spa.domain.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spa.domain.entity.Menu;
import com.spa.infrastructure.mapper.MenuMapStruct;
import com.spa.infrastructure.repository.condition.MenuCondition;
import com.spa.infrastructure.repository.po.MenuPO;
import com.spa.infrastructure.repository.po.RoleMenuRefPO;
import com.spa.infrastructure.repository.service.MenuRepositoryService;
import com.spa.infrastructure.repository.service.RoleMenuRefRepositoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MenuService {

    @Autowired
    private MenuRepositoryService menuRepositoryService;

    @Autowired
    private RoleMenuRefRepositoryService roleMenuRefRepositoryService;

    public int addMenu(MenuPO po) {
        return menuRepositoryService.addMenu(po);
    }

    public List<Menu> getAllMenus() {
        return MenuMapStruct.INSTANCE.po2Entity4List(menuRepositoryService.list(new MenuCondition()));
    }

    public List<Menu> getMenusByIds(long roleId) {
        List<RoleMenuRefPO> roleMenuRefPOS = roleMenuRefRepositoryService.listByRoleId(roleId);
        if (CollUtil.isEmpty(roleMenuRefPOS)) {
            return new ArrayList<>();
        }
        List<Long> ids = roleMenuRefPOS.stream().map(RoleMenuRefPO::getMenuId).toList();
        MenuCondition condition = new MenuCondition();
        condition.setIds(ids);
        return MenuMapStruct.INSTANCE.po2Entity4List(menuRepositoryService.list(condition));
    }

    public Page<Menu> pageMenus(MenuCondition condition) {
        return MenuMapStruct.INSTANCE.po2Entity4Page(menuRepositoryService.page(condition));
    }

}
